package com.ruoyi.web.controller.net;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementPortMode;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.net.service.SSHService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementPortLoopback;
import com.ruoyi.net.service.IElementPortLoopbackService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-loopback配置Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-接口-loopback配置")
@RestController
@RequestMapping("/element/port/loopback")
public class ElementPortLoopbackController extends BaseController {
    @Autowired
    private IElementPortLoopbackService elementPortLoopbackService;

    @Autowired
    private SSHService sshService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 读取
     */
    @ApiOperation(value = "读取", httpMethod = "GET")
    @GetMapping(value = "/read")
    public TableDataInfo read(ElementPortLoopback elementPortLoopback) {
        List<ElementPortLoopback> elementPortLoopbacks = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                "    <interfaces>" +
                "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                "        <type>LOOPBACK</type>" +
                "      </interface>" +
                "    </interfaces>" +
                "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortLoopback.getElementId());
        // TODO: 2024/12/9 从设备获取 接口信息
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            String rpcReply = deviceManager.getConfig(xml.toString());
            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortLoopback entity = new ElementPortLoopback();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setLoopbackId(getXmlLabelValue(node, "name"));
                    Node ipNode = getXmlLabelNode(node, "ip");
                    Node ipAddressNode = getXmlLabelNode(ipNode, "ipv4-address-list");
                    if (ipAddressNode != null) {
                        String ipv4 = getXmlLabelValue(ipAddressNode, "ipv4-address");
                        entity.setIp(StringUtils.isNotEmpty(ipv4) ? ipv4.split("/")[0] : "");
                        entity.setMask(StringUtils.isNotEmpty(ipv4) ? ipv4.split("/")[1] : "");
                        entity.setIpForm(getXmlLabelValue(ipAddressNode, "secondry-use"));
                    }
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementPortLoopbacks.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortLoopbacks);
    }

    /**
     * 查询网元-接口-loopback配置列表
     */
    @ApiOperation(value = "查询网元-接口-loopback配置列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:loopback:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortLoopback elementPortLoopback) {
        startPage();
        List<ElementPortLoopback> list = elementPortLoopbackService.selectElementPortLoopbackList(elementPortLoopback);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-loopback配置列表
     */
    @ApiOperation(value = "导出网元-接口-loopback配置列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:loopback:export')")
    @Log(title = "网元-接口-loopback配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortLoopback elementPortLoopback) {
        List<ElementPortLoopback> list = elementPortLoopbackService.selectElementPortLoopbackList(elementPortLoopback);
        ExcelUtil<ElementPortLoopback> util = new ExcelUtil<ElementPortLoopback>(ElementPortLoopback.class);
        util.exportExcel(response, list, "网元-接口-loopback配置数据");
    }

    /**
     * 获取网元-接口-loopback配置详细信息
     */
    @ApiOperation(value = "获取网元-接口-loopback配置详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:loopback:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortLoopbackService.selectElementPortLoopbackById(id));
    }

    /**
     * 新增网元-接口-loopback配置
     */
    @ApiOperation(value = "新增网元-接口-loopback配置", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:loopback:add')")
    @Log(title = "网元-接口-loopback配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortLoopback elementPortLoopback) {
        return toAjax(elementPortLoopbackService.insertElementPortLoopback(elementPortLoopback));
    }

    /**
     * 修改网元-接口-loopback配置
     */
    @ApiOperation(value = "修改网元-接口-loopback配置", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:loopback:edit')")
    @Log(title = "网元-接口-loopback配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortLoopback elementPortLoopback) {
        return toAjax(elementPortLoopbackService.updateElementPortLoopback(elementPortLoopback));
    }

    /**
     * 删除网元-接口-loopback配置
     */
    @ApiOperation(value = "删除网元-接口-loopback配置", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:loopback:remove')")
    @Log(title = "网元-接口-loopback配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortLoopbackService.deleteElementPortLoopbackByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @GetMapping(value = "/activate/{id}")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortLoopback elementPortLoopback = elementPortLoopbackService.selectElementPortLoopbackById(id);
        elementPortLoopback.setStatus("1");
        if (sendXml(elementPortLoopback)){
            return toAjax(elementPortLoopbackService.updateElementPortLoopback(elementPortLoopback));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortLoopback elementPortLoopback = elementPortLoopbackService.selectElementPortLoopbackById(id);
        elementPortLoopback.setStatus("0");
        if (sendXml(elementPortLoopback)){
            return toAjax(elementPortLoopbackService.updateElementPortLoopback(elementPortLoopback));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementPortLoopback entity) {
        boolean isSend = false;
        try {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            Device device = deviceManager.getDevice(netElement.getIp());
            if (device.isConnected()) {
                String xml = "";
                if ("1".equals(entity.getStatus())){
                    xml = "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                            "  <interfaces>" +
                            "   <interface>" +
                            "    <name>" + entity.getLoopbackId() + "</name>" +
                            "    <type>LOOPBACK</type>" +
//                            "    <enabled>" + ("1".equals(entity.getStatus()) ? "enable" : "disable") + "</enabled>" +
                            "       <enabled>enable</enabled>" +
                            "    <loopback-interface xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-if-loopback\"/>"+
                            "    <ip xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" +
                            "     <ipv4-address-list>" +
                            "      <ipv4-address>" + entity.getIp() + "/" + entity.getMask() + "</ipv4-address>" +
                            "      <secondry-use>mast</secondry-use>" +
                            "     </ipv4-address-list>" +
                            "    </ip>" +
                            "   </interface>" +
                            "  </interfaces>" +
                            " </if>";
                }else {
                    xml ="<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                            "        <interfaces>" +
                            "          <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"remove\">" +
                            "            <name>" + entity.getLoopbackId() + "</name>" +
                            "            <type>LOOPBACK</type>" +
                            "          </interface>" +
                            "        </interfaces>" +
                            "      </if>";
                }
                logger.info("Loopback 接口激活xml:" + xml);
                isSend = deviceManager.editConfig(xml, "merge");
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        return isSend;
    }
}